// 个人中心页面功能
(function () {
    var isPasswordVisible = false;
    var isLoading = false;

    // 初始化页面
    function initialize() {
        loadUserInfo();
        loadSystemStatus();
        setupEventListeners();
    }
    
    // 加载用户信息
    function loadUserInfo() {
        if (isLoading) return;
        isLoading = true;
        
        showLoadingState('userInfo');
        
        apiService.getUserProfile()
            .then(function (data) {
                console.log('用户信息数据:', data);
                updateUserInfo(data);
                hideLoadingState('userInfo');
            })
            .catch(function (err) {
                console.error('获取用户信息失败:', err);
                hideLoadingState('userInfo');
                showUserInfoError();
            })
            .finally(function() {
                isLoading = false;
            });
    }
    
    // 更新用户信息显示
    function updateUserInfo(data) {
        // 更新用户名
        var usernameEl = document.getElementById('username');
        if (usernameEl) {
            usernameEl.textContent = data.username || 'admin';
        }
        
        // 密码通过独立接口获取，这里只显示隐藏状态
        var passwordTextEl = document.getElementById('passwordText');
        if (passwordTextEl) {
            passwordTextEl.textContent = '••••••••';
        }
        
        // 更新最后登录时间
        var lastLoginEl = document.getElementById('lastLogin');
        if (lastLoginEl) {
            lastLoginEl.textContent = data.lastLogin || formatCurrentTime();
        }
        
        // 更新角色
        var roleBadge = document.querySelector('.role-badge');
        if (roleBadge) {
            roleBadge.textContent = data.role || '系统管理员';
        }
    }
    
    // 加载系统状态
    function loadSystemStatus() {
        apiService.getUserStatus()
            .then(function (data) {
                console.log('系统状态数据:', data);
                updateSystemStatus(data);
            })
            .catch(function (err) {
                console.error('获取系统状态失败:', err);
                showSystemStatusError();
            });
    }
    
    // 更新系统状态显示
    function updateSystemStatus(data) {
        // 更新在线状态
        var onlineStatusEl = document.getElementById('onlineStatus');
        if (onlineStatusEl) {
            onlineStatusEl.textContent = data.onlineStatus || '在线';
            onlineStatusEl.className = 'status-value ' + (data.onlineStatus === '在线' ? 'online' : 'offline');
        }
        
        // 更新权限级别
        var permissionLevelEl = document.getElementById('permissionLevel');
        if (permissionLevelEl) {
            permissionLevelEl.textContent = data.permissionLevel || '管理员';
        }
    }
    
    // 切换密码显示
    function togglePassword() {
        if (isPasswordVisible) {
            // 隐藏密码
            isPasswordVisible = false;
            var passwordTextEl = document.getElementById('passwordText');
            var toggleBtn = document.querySelector('.toggle-password-btn');
            
            if (passwordTextEl) {
                passwordTextEl.textContent = '••••••••';
            }
            
            if (toggleBtn) {
                toggleBtn.textContent = '👁️';
            }
        } else {
            // 显示密码，需要重新获取
            loadPassword();
        }
    }
    
    // 加载密码
    function loadPassword() {
        apiService.getUserPassword()
            .then(function (data) {
                console.log('密码数据:', data);
                showPassword(data.password);
            })
            .catch(function (err) {
                console.error('获取密码失败:', err);
                showPasswordError();
            });
    }
    
    // 显示密码
    function showPassword(password) {
        isPasswordVisible = true;
        var passwordTextEl = document.getElementById('passwordText');
        var toggleBtn = document.querySelector('.toggle-password-btn');
        
        if (passwordTextEl) {
            passwordTextEl.textContent = password || '••••••••';
        }
        
        if (toggleBtn) {
            toggleBtn.textContent = '🙈';
        }
    }
    
    // 显示密码错误状态
    function showPasswordError() {
        var passwordTextEl = document.getElementById('passwordText');
        var toggleBtn = document.querySelector('.toggle-password-btn');
        
        if (passwordTextEl) {
            passwordTextEl.textContent = '获取失败';
            passwordTextEl.style.color = '#dc3545';
        }
        
        if (toggleBtn) {
            toggleBtn.textContent = '❌';
        }
    }
    
    // 显示加载状态
    function showLoadingState(type) {
        if (type === 'userInfo') {
            var userInfoCard = document.querySelector('.user-info-card');
            if (userInfoCard) {
                userInfoCard.classList.add('loading');
            }
        }
    }
    
    // 隐藏加载状态
    function hideLoadingState(type) {
        if (type === 'userInfo') {
            var userInfoCard = document.querySelector('.user-info-card');
            if (userInfoCard) {
                userInfoCard.classList.remove('loading');
            }
        }
    }
    
    // 显示用户信息错误状态
    function showUserInfoError() {
        var usernameEl = document.getElementById('username');
        var lastLoginEl = document.getElementById('lastLogin');
        
        if (usernameEl) {
            usernameEl.textContent = '获取失败';
            usernameEl.style.color = '#dc3545';
        }
        
        if (lastLoginEl) {
            lastLoginEl.textContent = '无法获取';
            lastLoginEl.style.color = '#dc3545';
        }
    }
    
    // 显示系统状态错误状态
    function showSystemStatusError() {
        var onlineStatusEl = document.getElementById('onlineStatus');
        var permissionLevelEl = document.getElementById('permissionLevel');
        
        if (onlineStatusEl) {
            onlineStatusEl.textContent = '连接失败';
            onlineStatusEl.className = 'status-value error';
        }
        
        if (permissionLevelEl) {
            permissionLevelEl.textContent = '无法获取';
            permissionLevelEl.style.color = '#dc3545';
        }
    }
    

    // 设置事件监听器
    function setupEventListeners() {
        // 密码切换按钮
        var toggleBtn = document.querySelector('.toggle-password-btn');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', togglePassword);
        }
    }
    
    // 显示通知
    function showNotification(message, type) {
        // 创建通知元素
        var notification = document.createElement('div');
        notification.className = 'notification ' + type;
        notification.textContent = message;
        
        // 添加样式
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            animation: slideIn 0.3s ease;
        `;
        
        // 根据类型设置颜色
        switch (type) {
            case 'info':
                notification.style.background = '#3b82f6';
                break;
            case 'success':
                notification.style.background = '#10b981';
                break;
            case 'warning':
                notification.style.background = '#f59e0b';
                break;
            case 'error':
                notification.style.background = '#ef4444';
                break;
            default:
                notification.style.background = '#6b7280';
        }
        
        // 添加到页面
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(function() {
            notification.style.animation = 'slideOut 0.3s ease';
            setTimeout(function() {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }
    
    // 格式化当前时间
    function formatCurrentTime() {
        var now = new Date();
        var year = now.getFullYear();
        var month = String(now.getMonth() + 1).padStart(2, '0');
        var day = String(now.getDate()).padStart(2, '0');
        var hours = String(now.getHours()).padStart(2, '0');
        var minutes = String(now.getMinutes()).padStart(2, '0');
        var seconds = String(now.getSeconds()).padStart(2, '0');
        
        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    }
    
    // 添加CSS动画
    function addNotificationStyles() {
        if (document.getElementById('notification-styles')) return;
        
        var style = document.createElement('style');
        style.id = 'notification-styles';
        style.textContent = `
            @keyframes slideIn {
                from {
                    transform: translateX(100%);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }
            
            @keyframes slideOut {
                from {
                    transform: translateX(0);
                    opacity: 1;
                }
                to {
                    transform: translateX(100%);
                    opacity: 0;
                }
            }
        `;
        document.head.appendChild(style);
    }
    
    // 页面加载时初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            addNotificationStyles();
            initialize();
        });
    } else {
        addNotificationStyles();
        initialize();
    }
    
    // 将函数暴露到全局作用域
    window.togglePassword = togglePassword;
})();